import MapItem from "./MapItem";
import {mapBase} from "../base/common/Constants";
import {getBorder, OmitName} from "../base/utils/Utils";
import List from "../Common/List";
import BuildItem from "./BuildItem";

const {ccclass, property} = cc._decorator;

// import executeInEditMode = cc._decorator.executeInEditMode;

enum MapType {
    wall,  // 障碍
    get,   // 接单
    push,  // 放单
    road,  // 路
    spawn, // 出生点
    none, // 无状态
}

export const getBuildName=[
    '小明烧烤',
    '黄大妈木桶饭',
    '潮汕海鲜砂锅粥',
    '原味汤粉王',
    '东北馅饼',
    '台湾手抓饼',
    '华莱士全鸡汉堡',
    '茶百道',
]

export const pushBuildName=[
    '1号楼',
    '2号楼',
    '3号楼',
    '4号楼',
    '5号楼',
    '6号楼',
    '7号楼',
    '8号楼',
    '9号楼',
    '10号楼',
    '11号楼',
    '12号楼',
    '13号楼',
    '14号楼',
    '15号楼',
    '16号楼',
    '17号楼',
    '18号楼',
    '19号楼',
    '20号楼',
    '29号楼',
    '30号楼',
    '31号楼',
    '32号楼',
    '33号楼',
    '34号楼',
    '35号楼',
    '36号楼',


]


@ccclass
// @executeInEditMode()
export default class MapLogic extends cc.Component {

    @property(cc.Node) item: cc.Node = null;
    @property(cc.Node) mapParent: cc.Node = null;

    @property(cc.Node) enemyParent: cc.Node = null;
    @property(cc.Node) enemyItem: cc.Node = null;


    @property(cc.Node) typeNode: cc.Node = null;

    @property(cc.Node) proNode:cc.Node = null;

    mapData: mapBase[] = [];

    currentType: MapType = MapType.wall;

    enemyPos: number[][] = [[]];

    @property(List)
    buildList: List = null;

    buildData =[];

    curItem:MapItem = null;
    curT:number = -1;


    onClickType(event, type) {
        this.currentType = parseInt(type);
        for (let i = 0; i < this.typeNode.childrenCount; i++) {
            this.typeNode.children[i].children[0].color = i == this.currentType ? cc.Color.RED : cc.Color.WHITE;
        }
    }

    /**
     * 动态加载省份数据显示
     * @param node
     * @param idx
     */
    onProvinceListRender(node: cc.Node, idx: number) {
        node.getComponent(BuildItem).init(this.buildData[idx],  this);
    }


    /**
     *
     * @param t  0 放   1 取
     */
    showPro(t,item){
        this.proNode.active = true;

        this.curItem = item;
        this.curT = t;
        this.buildData = [];
        let arr = t == 0 ? pushBuildName : getBuildName;
        for (let i = 0; i < arr.length; i++) {
            this.buildData.push(arr[i]);
        }
        this.buildList.numItems = this.buildData.length;
    }

    sureBuild(t){

        if(this.curItem != null){
            console.log(this.curT);
            if(this.curT == 0){
                this.curItem.decLabel.string = OmitName(4,pushBuildName[t]);
                this.curItem.mapData.pushBuild = t;
                console.log(this.curItem.decLabel.string);
                console.log(this.curItem.node);
            }else {
                this.curItem.decLabel.string = OmitName(4,getBuildName[t]);
                this.curItem.mapData.getBuild = t;
            }
        }
        this.curItem = null;
        this.proNode.active = false;

    }

    protected onLoad() {
        this.init();
        this.onDrag();
    }

    init() {
        this.mapParent.destroyAllChildren();
        this.mapData = [];
        this.enemyPos = [];
        for (let i = 0; i < 19; i++) {
            for (let j = 0; j < 11; j++) {
                let node = cc.instantiate(this.item);
                node.setParent(this.mapParent);
                let id = i * 11 + j;
                let xx = i ;
                let yy = j;
                node.children[1].getComponent(cc.Label).string = `${xx},${yy}`;
                // node.children[1].getComponent(cc.Label).string = `${id}`;
                this.mapData.push({
                    id: id,
                    x: xx,
                    y: yy,
                    open: 1,
                    pushBuild: -1,  // 放单点
                    getBuild: -1,  // 接单点
                    spawn_point: 0,  // 出生点

                })
                node.getComponent(MapItem).init({
                    id: id,
                    x: xx,
                    y: yy,
                    open: 1,
                    pushBuild: -1,  // 放单点
                    getBuild: -1,  // 接单点
                    spawn_point: 0,  // 出生点
                },this);
            }
        }
        // console.log(this.mapData);
        // console.log(JSON.stringify(this.mapData));
    }

    hideLabel(){
        for(let i = 0; i <this.mapParent.childrenCount; i++){
            this.mapParent.children[i].children[1].getComponent(cc.Label).enabled =false;
        }
    }

    showLabel(){
        for(let i = 0; i <this.mapParent.childrenCount; i++){
            this.mapParent.children[i].children[1].getComponent(cc.Label).enabled =true;
        }
    }

    //拖拽注册
    onDrag() {
        this.node.on(cc.Node.EventType.TOUCH_MOVE, this.touchMove, this);
        this.node.on(cc.Node.EventType.TOUCH_START, this.touchStart, this);
        this.node.on(cc.Node.EventType.TOUCH_CANCEL, this.touchEnd, this);
        this.node.on(cc.Node.EventType.TOUCH_END, this.touchEnd, this);

    }

    //拖拽注销
    offDrag() {
        this.node.off(cc.Node.EventType.TOUCH_MOVE, this.touchMove, this);
        this.node.off(cc.Node.EventType.TOUCH_START, this.touchStart, this);
        this.node.off(cc.Node.EventType.TOUCH_CANCEL, this.touchEnd, this);
        this.node.off(cc.Node.EventType.TOUCH_END, this.touchEnd, this);
    }

    touch: boolean = false;
    touchId: number[] = [];

    touchStart(event: cc.Touch) {
        this.touchId = [];
        // console.log('开始点击:::')

    }

    touchMove(event) {
        // console.log('点击:::')
        if(this.currentType == MapType.none){
            return
        }
        const p = event.getLocation();


        this.mapLogic(p);

    }


    touchEnd(event: cc.Touch) {
        // console.log('结束点击:::')
        if(this.currentType == MapType.none){
            return
        }
        const p = event.getLocation();
        this.mapLogic(p);
        // console.log(this.mapBigNode);
        // console.log(this.mapData);
        // console.log(JSON.stringify(this.mapData));
    }

    mapLogic(p) {
        const borders = this.mapParent.children.map(getBorder);

        for (let i = 0; i < borders.length; i++) {
            const b = borders[i];
            if (
                this.mapParent.children[i].active && (
                    p.x > b.left &&
                    p.x < b.right &&
                    p.y > b.bottom &&
                    p.y < b.top)
            ) {

                let component = this.mapParent.children[i].getComponent(MapItem);
                if (this.touchId.some(value => value == component.mapData.id)) {
                    return;
                }
                component.changeMap(this.currentType);
                this.touchId.push(component.mapData.id);
                let mapBase = this.mapData.findIndex(value => value.id == component.mapData.id);
                if (mapBase != -1) {
                    this.mapData[mapBase] = component.mapData;
                }


            }
        }
    }

    onClickSave() {
        this.creatJosnFile(this.mapData, 'level')
    }


    /**生成json文件 */
    creatJosnFile(data: any, fileName: string) {
        let d = {
            pos: [0, 0],
            data: data,
            enemy: this.enemyPos
        }
        var content = JSON.stringify(d)
        this.saveForBrowser(content, fileName)
    }

    /**
     * 存字符串内容到文件。
     * @param textToWrite  - 要保存的文件内容
     * @param fileNameToSaveAs - 要保存的文件名
     */
    saveForBrowser(textToWrite, fileNameToSaveAs) {
        if (cc.sys.isBrowser) {
            cc.log("浏览器");
            let textFileAsBlob = new Blob([textToWrite], {type: 'application/json'});
            let downloadLink = document.createElement("a");
            downloadLink.download = fileNameToSaveAs;
            downloadLink.innerHTML = "Download File";
            if (window.webkitURL != null) {
                downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
            }
            downloadLink.click();
        }
    }

}
